// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#pragma once

#include <functional>
#include <string>

namespace kumo::pollux::process {
    // Used to store thread local information which can be retrieved by a signal
    // handler and logged.
    struct ThreadDebugInfo {
        std::string queryId_;
        std::string taskId_;
        // Callback to invoke when the debug info is to be dumped. Can be empty.
        std::function<void()> callback_;
    };

    // A RAII class to store thread local debug information.
    class ScopedThreadDebugInfo {
    public:
        explicit ScopedThreadDebugInfo(const ThreadDebugInfo &localDebugInfo);

        explicit ScopedThreadDebugInfo(const ThreadDebugInfo *localDebugInfo);

        ~ScopedThreadDebugInfo();

    private:
        const ThreadDebugInfo *prevThreadDebugInfo_ = nullptr;
    };

    // Get the current thread local debug information. Used by signal handlers or
    // can be accessed during a debug session. Returns nullptr if no debug info is
    // set.
    const ThreadDebugInfo *GetThreadDebugInfo();

    // Install a signal handler to dump thread local debug information. This should
    // be called before calling melon::symbolizer::installFatalSignalCallbacks()
    // which is usually called at startup via melon::Init init{}. This is just a
    // default implementation but you can install your own signal handler. Make sure
    // to install one at the start of your program.
    void addDefaultFatalSignalHandler();
} // namespace kumo::pollux::process
